// 版本1
const http = require('http')
const fs = require('fs')
const server = http.createServer((request, response) => {
    // response.end('hello ...')
    const { url, method ,headers} = request
    if (url === '/' && method === 'GET'){
        // 静态页面服务
        fs.readFile('index.html',(err,data) => {
            if(err){
                console.log("500")
                response.writeHead(500,{
                    // writeHead会把东西全读到内存去，内存占用大，在html处还不显著，但是在图片处使用的吧话就会消耗大量内存
                    'Content-Type':'text/plain;charset=utf-8'
                })
                response.end('500 服务器挂了')
                return
            }
            response.statusCode = 200
            response.setHeader('Content-Type','text/html')
            response.end(data)
            console.log("200")
        })
    }else if(url === '/users' && method === 'GET'){
        // Ajax服务
        response.writeHead(200,{
            'Content-Type': 'application/json'
        })
        response.end(JSON.stringify({
            name : 'qyx'
        }))
    }else if(method === 'GET' && headers.accept.indexOf('image/*') !== -1){
        // 图片文件服务
        fs.createReadStream('./'+url).pipe(response)
    }else {
        console.log("404")
        response.statusCode=404
        response.setHeader('Content-Type','text/plain;charset=utf-8')
        reponse.end('404没这玩意')
    }

})

// 监听端口
server.listen(8888,()=>{
    console.log('Server at 8888')
})


